import React from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Route, Redirect } from 'react-router'
import { global as userDuck } from 'ducks'

const createRedirect = ({ location }) => ({
  pathname: '/',
  state: {
    returnURL: location.pathname,
  },
})

const PublicRoute = ({
  component: Component, isSignedIn, isAuthed, path, ...rest
}) => {
  const render = !isSignedIn && !isAuthed
    ? props => <Component {...props} />
    : props => <Redirect path={path} to={createRedirect(props)} />

  return <Route {...rest} render={render} />
}

PublicRoute.propTypes = {
  component: PropTypes.func.isRequired,
  isSignedIn: PropTypes.bool.isRequired,
}

const mapStateToProps = state => ({
  isSignedIn: userDuck.selectors.isSignedIn(state),
  isAuthed: userDuck.selectors.isAuthed(state),
})

export default connect(mapStateToProps)(PublicRoute)
